<?php

namespace App\Http\Controllers\Admin\V1;

use App\Models\Role;
use App\Models\Question;
use App\Models\TestList;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Exports\TestListExport;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\TestListRequest;
use App\Transformers\Admin\TestListTransformer;
use Illuminate\Auth\Access\AuthorizationException;
use App\Http\Requests\Admin\SelectQuestionsRequest;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class TestListController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        // 判断是否拥有查看所有数据的权限
        $root = auth()->user()->hasRole(Role::SUPER_ADMIN);

        $ids = userIdAndAllChildrenId();

        // 获取试卷列表
        $data = TestList::query()
            ->select('id', 'name', 'user_id', 'paper_id', 'status', 'subject_id', 'created_at')
            // 有权限不走此判断查询所有，无权限只查自己和子级
            ->when(!$root, function ($query) use ($ids) {
                $query->whereIn('user_id', $ids);
            })
            ->pimp()
            ->orderBy('created_at', 'DESC')
            ->Paginate($this->pageLimit());

        return $this->response->paginator($data, new TestListTransformer());
    }

    /**
     *
     * 添加前需要获取的分类数据
     *
     * @return \Dingo\Api\Http\Response
     */
    public function add()
    {
        // 获取试卷分类
        $paper = cachePaper();

        // 获取科目分类
        $subject = cacheSubject();

        return $this->response->array(['paper' => $paper, 'subject' => $subject]);
    }

    /**
     *
     * 添加时查询的试题数据
     *
     * @param SelectQuestionsRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function selectQuestions(SelectQuestionsRequest $request)
    {
        // 获取试题各难度数量
        $data['level'] = Question::query()->groupBy('level')
            ->select(DB::raw('count(*) as sum, level'))
            ->where('category_id', $request->input('category_id'))
            ->where('type', $request->input('type'))
            ->where('status', 1)
            ->get();

        $data['allNum'] = 0;
        foreach ($data['level'] as $v) {
            $data['allNum'] += $v['sum'];
        }

        return $this->response->array($data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param TestListRequest $request
     * @return Response
     * @throws AuthorizationException
     */
    public function store(TestListRequest $request)
    {

        $this->authorize('create', TestList::class);

        $request['user_id'] = auth()->id();

//        $request['random'] = json_decode($request->input('random'));

        $data = TestList::create($request->all());

        return $this->response->array(['data' => $data]);
    }

    /**
     * Display the specified resource.
     *
     * @param TestList $test_list
     * @return Response
     */
    public function show(TestList $test_list)
    {
        // 获取试卷分类
        $paper = cachePaper();

        // 获取科目分类
        $subject = cacheSubject();

        // 获取试卷详情
        $data = $test_list->query()
            ->select('id', 'name', 'user_id', 'paper_id', 'subject_id', 'type', 'status', 'order', 'random', 'fixed', 'artificial')
            ->where('id', $test_list->id)
            ->get();

        return $this->response->array(['paper' => $paper, 'subject' => $subject, 'data' => $data]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param TestListRequest $request
     * @param TestList $test_list
     * @return Response
     * @throws AuthorizationException
     */
    public function update(TestListRequest $request, TestList $test_list)
    {
        $this->authorize('update', $test_list);

        $test_list->update($request->all());
        return $this->response->noContent();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param $ids
     * @return \Dingo\Api\Http\Response
     * @throws AuthorizationException
     */
    public function destroy($ids)
    {
        // 分割传过来的id
        $idArr = explode(',', $ids);

        foreach (TestList::whereIn('id', $idArr)->get() as $model) {
            // 验证授权
            $this->authorize('delete', $model);

            // 执行删除
            $model->delete();
        }

        return $this->response->noContent();
    }

    /**
     *
     * 试卷复制方法
     *
     * @param TestList $test_list
     * @return \Dingo\Api\Http\Response
     */
    public function copy(TestList $test_list)
    {
        $data = $test_list->toArray();

        unset($data['id'], $data['created_at'], $data['updated_at']);
        $data['name'] = $data['name'] . '_复制';
        $data['user_id'] = auth()->id();

        TestList::create($data);
        return $this->response->created();
    }

    /**
     *
     * 试卷预览
     *
     * @param TestList $test_list
     * @param Request $request
     * @return \Dingo\Api\Http\Response
     */
    public function preview(TestList $test_list, Request $request)
    {
        $type = $request->input('type');

        $data = testQuestion($test_list, $type);

        return $this->response->array(['data' => $data]);
    }

    /**
     *
     * 试卷导出
     *
     * @param TestList $test_list
     * @param Request $request
     * @return Response|BinaryFileResponse
     */
    public function export(TestList $test_list, Request $request)
    {
        $type = $request->input('type');

        return (new TestListExport($test_list, $type))->download('testList.xlsx');
    }
}
